package cate.game.role.merge;

import cate.game.GameBody;
import cate.game.framework.ModuleManager;
import cate.game.role.Role;
import cate.game.role.base.RoleBase;
import cp.solution.ops.status.SysOprStatus;
import cp.solution.util.time.TimeCostRecord;
import easy.java.time.DateTool;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.function.Consumer;

/** 角色遍历 */
@Slf4j
public class RoleTraversal implements ModuleManager {

    private GameBody game;

    @Override
    public void initIndependent(GameBody game) throws Exception {
        this.game = game;
    }

    @Override
    public void initDependent() throws Exception {

    }

    public void doMergeSettle(SysOprStatus sos) {
        TimeCostRecord tcr = new TimeCostRecord();
        __do__(game, sos, tcr, (role) -> {
            role.onMergeSettle(game, tcr);
            role.save();
        });
    }

    public void doCleanData(SysOprStatus sos) {
        TimeCostRecord tcr = new TimeCostRecord();
        __do__(game, sos, tcr, (role) -> {
            // 判断这个角色是否有效，无效的就清理掉
            RoleCleaner.exe(game, sos, tcr, role);
            //
            try {
                Thread.sleep(20);
            } catch (Exception e) {
                log.error("", e);
            }
        });
    }

    private static void __do__(GameBody game, SysOprStatus sos, TimeCostRecord tcr, Consumer<Role> consumer) {
        long beginTime = System.currentTimeMillis();
        List<RoleBase> rbs = game.facilities.getMongo().roleBase.findAll();
        final int roleNum = rbs.size();
        sos.setRolesNumTotal(roleNum);
        log.info("本服有角色数={}", roleNum);

        for(RoleBase rb : rbs) {
            Role role = game.role.getRole(rb.uid, true);
            if(role == null) {
                log.error("居然没找到={}", rb.uid);
                continue;
            }
            consumer.accept(role);
            log.info("名字={} {}", role.getBase().name, DateTool.instance().format(role.getStatus().createTime));
            sos.increaseRolesNumDone();
        }

        long costTime = System.currentTimeMillis() - beginTime;
        long perCost = costTime / roleNum;
        String description = "处理完毕 耗时"+costTime+"ms, 角色数="+roleNum+", 人均耗时="+perCost
                +"ms, activeNum="+game.role.getActiveNum() + "。 " + tcr.toDescription();
        log.info(description);
        sos.rolesDone();
    }

}
